package br.com.mundoj.subscription.client;

import br.com.mundoj.subscription.client.events.SaveSubscriptionEvent;
import br.com.mundoj.subscription.client.events.SearchAddressByCepEvent;
import br.com.mundoj.subscription.client.services.CepService;
import br.com.mundoj.subscription.client.view.SubscriptionView;

import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;

public class SubscriptionManager {
	private final SubscriptionView view;
	
	@Inject
	public SubscriptionManager(HandlerManager eventBus, 
			final SubscriptionView view, final CepService cepService) {
		this.view = view;
		
		eventBus.addHandler(SearchAddressByCepEvent.TYPE, new SearchAddressByCepEvent.Handler() {
			@Override
			public void onEvent(SearchAddressByCepEvent e) {
				cepService.execute(e.formattedCep.formatted, 2000, new CepService.Callback() {
					@Override
					public void execute(ILocationData loc) {
						view.updateAddressData(loc);
					}
				});
			}
		});
		
		eventBus.addHandler(SaveSubscriptionEvent.TYPE, new SaveSubscriptionEvent.Handler() {
			@Override
			public void onEvent(SaveSubscriptionEvent event) {
				Subscription s = event.subscription;
				Person p = s.getPerson();
				Address a = p.getAddress();
				ContactData c = p.getContacts();
				
				StringBuilder debug = 
					new StringBuilder(p.getType().name()).append("\n")
					.append(p.getDocument()).append("\n")
					.append(p.getName()).append("\n")
					.append(p.getEmail()).append("\n")
					.append(p.getGender()).append("\n")
					.append(p.getBirthDate()).append("\n")
					.append(a.getCep()).append("\n")
					.append(a.getCity()).append("\n")
					.append(a.getState()).append("\n")
					.append(a.getAddress()).append("\n")
					.append(a.getComplement()).append("\n")
					.append(a.getNeighborhood()).append("\n")
					.append(c.getHomePhone()).append("\n")
					.append(c.getWorkPhone()).append("\n")
					.append(c.getFaxNumber()).append("\n")
					.append(s.getPaymentMethod()).append("\n")
					.append(s.getStartingEdition()).append("\n")
					.append(s.getReference());
				Window.alert(debug.toString());
			}
		});
	}

	public Widget getView() {
		return view;
	}
}